#include "stdafx.h"
#include <math.h>
#include "AniObject.h"
#include "MemTrack.h"

namespace bs
{
	AniObject::AniObject()
		: x(0), y(0), w(0), h(0), z(0), name(""), type(0), playing(false), paused(false),
		visible(true), moveAble(false), autoStop(true), vx(0.0f), vy(0.0f), sx(0), sy(0), dx(0), dy(0)
	{
	}

	AniObject::~AniObject()
	{
	}

	void AniObject::Start()
	{
		if(this->playing)
			return;

		this->playing = true;
		this->paused = false;

		this->StartMovement();
	}

	void AniObject::Stop()
	{
		this->playing = false;
		this->paused = false;
	}

	void AniObject::Pause()
	{
		if(!this->playing || this->paused)
			return;

		this->paused = true;
	}

	void AniObject::Resume()
	{
		if(!this->paused)
			return;

		this->paused = false;
	}

	void AniObject::Update( int elapsed, float speedFactor /*= 1.0f*/ )
	{
		if(!this->playing || this->paused)
			return;

		this->Move(speedFactor);
	}

	void AniObject::Draw( HDC dc )
	{
	}

	void AniObject::SetMovement( float vel, int _dx, int _dy )
	{
		return SetMovement(vel, (int)this->x, (int)this->y, _dx, _dy);
	}

	void AniObject::SetMovement( float vel, int _sx, int _sy, int _dx, int _dy )
	{
		if(_sx==_dx && _sy==_dy)
		{
			this->moveAble = false;
			return;
		}

		if(vel < 0)
			vel = -vel;

		this->sx = _sx;
		this->sy = _sy;
		this->dx = _dx;
		this->dy = _dy;

		float dist = ::sqrt(::pow((float)dy-sy, 2) + ::pow((float)dx-sx, 2));
		this->vx = vel * (dx-sx) / dist;
		this->vy = vel * (dy-sy) / dist;

		this->moveAble = true;
	}

	void AniObject::StartMovement()
	{
		if(this->moveAble)
		{
			this->x = (float)this->sx;
			this->y = (float)this->sy;
		}
	}

	void AniObject::Move(float speedFactor)
	{
		if(!this->moveAble)
			return;

		int preXSign = this->dx - (int)this->x;
		int preYSign = this->dy - (int)this->y;

		this->x += this->vx * speedFactor;
		this->y += this->vy * speedFactor;

		int postXSign = this->dx - (int)this->x;
		int postYSign = this->dy - (int)this->y;

		if(preXSign*postXSign<=0 && preYSign*postYSign<=0)
		{
			this->moveAble = false;
		}

		if(!this->moveAble && this->autoStop)
		{
			this->playing = false;
		}
	}
}

